<?php
/**
 * This file is part of workerman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link http://www.workerman.net/
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */

/**
 * 用于检测业务代码死循环或者长时间阻塞等问题
 * 如果发现业务卡死，可以将下面declare打开（去掉//注释），并执行php start.php reload
 * 然后观察一段时间workerman.log看是否有process_timeout异常
 */
//declare(ticks=1);

use \GatewayWorker\Lib\Gateway;
use think\Cache;
/**
 * 主逻辑
 * 主要是处理 onConnect onMessage onClose 三个方法
 * onConnect 和 onClose 如果不需要可以不用实现并删除
 */
class Events
{
//    public static function onConnect($client_id)
//    {
//        //发送当前在线人数
//        $pnum = Gateway::getAllClientIdCount();
//        $msg = [
//            'pnum'=>$pnum,
//            'client_id'=>$client_id,
//            'msg_type'=>'pnum'
//        ];
//        Gateway::sendToCurrentClient(json_encode($msg));
//    }
    /**
     * 当客户端发来消息时触发
     * @param int $client_id 连接id
     * @param mixed $message 具体消息
     */
    public static function onMessage($client_id, $message)
    {
        // debug
        echo "client:{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']} gateway:{$_SERVER['GATEWAY_ADDR']}:{$_SERVER['GATEWAY_PORT']}  client_id:$client_id session:".json_encode($_SESSION)." onMessage:".$message."\n";

        // 客户端传递的是json数据
        $message_data = json_decode($message, true);
        if(!$message_data)
        {
            return ;
        }
        //连接本地的 Redis 服务
        $redis = new Redis();
        $redis->connect('127.0.0.1', '6906');//以下注释行为redis密码，如需要请开启
        $redis->auth('');
        // 根据类型执行不同的业务
        switch($message_data['msg_type'])
        {
            // 客户端回应服务端的心跳
            case 'pong':
                // 获取私董会房间内所有用户列表
                $room_id = '999999999';
                $clients_list = Gateway::getClientSessionsByGroup($room_id);
                $new_message = [
                    'msg_type'=>'userlist',
                    'data'=>$clients_list
                ];
                    Gateway::sendToGroup($room_id, json_encode($new_message));
                break;
            // 客户端登录 message格式: {type:login, name:xx, room_id:1} ，添加到客户端，广播给所有客户端xx进入聊天室
            case 'login':
                // 判断是否有房间号
                if(!isset($message_data['zbid']))
                {
                    throw new \Exception("\$message_data['room_id'] not set. client_ip:{$_SERVER['REMOTE_ADDR']} \$message:$message");
                }
                // 把房间号昵称放到session中
                $room_id = $message_data['zbid'];
                $client_name = htmlspecialchars($message_data['nickname']);
                $_SESSION['room_id'] = $room_id;
                $_SESSION['client_name'] = $client_name;//昵称
                $_SESSION['avatar'] = htmlspecialchars_decode($message_data['avatar']);//头像
                $_SESSION['uid'] = $message_data['uid'];//uid
                // 获取房间内所有用户列表
                $clients_list = Gateway::getClientSessionsByGroup($room_id);
                // 转播给当前房间的所有客户端，xx进入聊天室 message {type:login, client_id:xx, name:xx}
                $new_message = array('type'=>$message_data['msg_type'], 'client_id'=>$client_id, 'client_name'=>htmlspecialchars($client_name), 'time'=>date('Y-m-d H:i:s'));
                Gateway::joinGroup($client_id, $room_id);
                Gateway::sendToGroup($room_id, $message);
                Gateway::sendToCurrentClient(json_encode($new_message));
                break;
            // 直播聊天室
            case 'say':
                // 非法请求
                if(!isset($_SESSION['room_id']))
                {
                    throw new \Exception("\$_SESSION['room_id'] not set. client_ip:{$_SERVER['REMOTE_ADDR']}");
                }
                $room_id = $_SESSION['room_id'];
                $message_data['time'] = date('Y-m-d H:i:s');
                Gateway::sendToGroup($room_id ,json_encode($message_data));
                break;
            //村长广播
            case 'guangbo':
                Gateway::sendToAll($message);
                break;
            case 'sys_login':
                $pnum = Gateway::getAllClientIdCount();//当前人数
                $message_data['pnum'] = $pnum;
                if(isset($message_data['uid'])){
                    Gateway::bindUid($client_id, $message_data['uid']);
                }
                Gateway::sendToCurrentClient(json_encode($message_data));
                if(Gateway::isUidOnline($message_data['uid']) == 1){
//                    Gateway::sendToUid($message_data['uid'], json_encode($message_data));// 在线就转发消息给对应的uid
                    //查询是否有离线留言 有则转发
                    $msgList = $redis->lrange('wenda_msg'.$message_data['uid'],0,-1);
                    $msgList = array_reverse($msgList);
                    if(!empty($msgList)){
                        foreach ($msgList as $k=>$v){
                            Gateway::sendToUid($message_data['uid'], $v);// 在线就转发消息给对应的uid
                            $redis->lrem('wenda_msg'.$message_data['uid'],$v,1);
                        }
                    }
                }
                break;
        }
    }


    /**
     * 当客户端断开连接时
     * @param integer $client_id 客户端id
     */
    public static function onClose($client_id)
    {
        // debug
        echo "client:{$_SERVER['REMOTE_ADDR']}:{$_SERVER['REMOTE_PORT']} gateway:{$_SERVER['GATEWAY_ADDR']}:{$_SERVER['GATEWAY_PORT']}  client_id:$client_id onClose:''\n";

        // 从房间的客户端列表中删除
        if(isset($_SESSION['room_id']))
        {
            $room_id = $_SESSION['room_id'];
            $new_message = array('type'=>'logout', 'from_client_id'=>$client_id, 'from_client_name'=>$_SESSION['client_name'], 'time'=>date('Y-m-d H:i:s'));
            Gateway::sendToGroup($room_id, json_encode($new_message));
        }
    }
}
